package com.dotflat.satistics.utils;

import java.math.BigDecimal;
import java.math.RoundingMode;

/**
 * *******************************
 * Created by Tim.
 * form com.matt
 * on 2018/7/11
 * *******************************
 */
public class MathUtil {
    public static Double divide(Integer dividend, Integer divisor) {
        if (dividend == 0 && divisor ==0)
            return 0.0;
        return divisor == 0 ? 1 : BigDecimal.valueOf(dividend).divide(BigDecimal.valueOf(divisor), 2, RoundingMode.HALF_UP).doubleValue();
    }

    public static Double divide(Long dividend, Long divisor) {
        if (dividend == 0 && divisor ==0)
            return 0.0;
        return divisor == 0 ? 1 : BigDecimal.valueOf(dividend).divide(BigDecimal.valueOf(divisor), 2, RoundingMode.HALF_UP).doubleValue();
    }

    public static Double divide(Double dividend, Double divisor) {
        if (dividend == 0 && divisor ==0)
            return 0.0;
        return divisor == 0 ? 1 : BigDecimal.valueOf(dividend).divide(BigDecimal.valueOf(divisor), 2, RoundingMode.HALF_UP).doubleValue();
    }

    public static Double growRate(Double lastDouble, Double nowDouble){
        if (lastDouble == 0 || (nowDouble <=lastDouble))
            return 0.0;
        return BigDecimal.valueOf(nowDouble-lastDouble).divide(BigDecimal.valueOf(lastDouble), 2, RoundingMode.HALF_UP).doubleValue();

    }

    public static Double floatValue(Double one , Double two){
        return divide(subtract(one, two), two);
    }



    public static BigDecimal divide(BigDecimal dividend, BigDecimal divisor) {
        if (dividend.compareTo(BigDecimal.ZERO) == 0 && divisor.compareTo(BigDecimal.ZERO) == 0)
            return BigDecimal.ZERO;
        return divisor.compareTo(BigDecimal.ZERO) == 0 ? BigDecimal.ONE : dividend.divide(divisor, 2, RoundingMode.HALF_UP);
    }

    public static Double plus(Double dividend, Double divisor) {
        return BigDecimal.valueOf(dividend).add(BigDecimal.valueOf(divisor)).doubleValue();
    }

    public static Double plus(Long addend1, Long addend2) {
        return plus(Double.valueOf(addend1), Double.valueOf(addend2));
    }


    public static Double subtract(Double minuend, Double subtrahend) {
        return BigDecimal.valueOf(minuend).subtract(BigDecimal.valueOf(subtrahend)).doubleValue();
    }

    public static Double multiply(Double multiplicand, Double multiplier) {
        if (multiplicand == 0 && multiplier ==0)
            return 0.0;
        return multiplier == 0 ? 1 : BigDecimal.valueOf(multiplicand).multiply(BigDecimal.valueOf(multiplier)).doubleValue();
    }


    public static int doubleToInt(double number) {
        BigDecimal bd = new BigDecimal(number).setScale(0, BigDecimal.ROUND_HALF_UP);
        return bd.intValue();
    }

    public static void main(String[] args) {
        System.out.println(floatValue(96d, 100d));
        System.out.println(growRate(10d,15d));
    }
}
